<?php
namespace Home\Controller;
use Think\Controller;
class LoginController extends CommonController {
    public function index(){
    	$question = D('Verify')->getRandOne();

    	$this->assign('question',$question);

      $this->assign('title','登录');

        $this->display();
    }

    public function checkdata()
    {
    	$data = I('post.');

    	$vercode = I('post.vercode');

      	if($vercode!=$_SESSION['answer']){

      		$this->ajaxReturn(['error'=>1,'info'=>'人类验证不通过']);
      	}


      	$user = M('user')->where(['email'=>$data['email'],'password'=>md5($data['password'])])->find();


      	if($user){

          if($user['status']=='1'){
            $this->ajaxReturn(['error'=>1,'info'=>'用户被停用，请联系管理员']);
          }

      		$_SESSION['uid'] = $user['uid'];
      		$_SESSION['nickname'] = $user['nickname'];
      		$_SESSION['face'] = $user['face'];

      		$this->ajaxReturn(['error'=>0,'info'=>'登录成功']);

      	}else{

      		$this->ajaxReturn(['error'=>1,'info'=>'邮箱密码不正确']);

      	}



    }

    public function logout()
    {
    	session_unset();
    	session_destroy();

    	$this->success('退出成功', U('home/login/index'));
    }

    public function wxLogin()
    {

      $appid = "wxbac82045a637c02e";

      $reutrnUrl = "http://1o533n8683.imwork.net".U('home/login/wxreturn');

      $reutrnUrl = urlencode($reutrnUrl);

        
      $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appid."&redirect_uri=".$reutrnUrl."&response_type=code&scope=snsapi_base&state=123#wechat_redirect";

      header("Location:".$url);
    }

    public function wxreturn()
    {

       $appid = "wxbac82045a637c02e";
       $secret = "7c320fea54e77a01fcc59ff7060b04e2";
      $code = $_GET['code'];

      $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$secret."&code=".$code."&grant_type=authorization_code";

        $data = file_get_contents($url);

        $data = json_decode($data,true);


        $openid = $data['openid'];

        $user = M('user')->where(['wxopenid'=>$openid])->find();


        if($user){

          $_SESSION['uid'] = $user['uid'];
          $_SESSION['nickname'] = $user['nickname'];
          $_SESSION['face'] = $user['face'];

          $this->success('登录成功',U('home/index/index'));

        }else{

          $user = $this->wxUserInfo($data);

          $face = $this->getFace($user['headimgurl']);

          $data['nickname'] = $user['nickname'];
          $data['face'] = $face;
          $data['city'] = $user['city'];
          $data['sex'] = $user['sex']==1?'男':'女';
          $data['ctime'] = time();
          $data['wxopenid'] = $openid;

          $uid = M('user')->add($data);


          $_SESSION['uid'] = $uid;
          $_SESSION['nickname'] = $data['nickname'];
          $_SESSION['face'] = $data['face'];

          $this->success('登录成功',U('home/index/index'));

        }
    }

    public function wxUserInfo($data)
    {
      
      $url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$data['access_token']."&openid=".$data['openid']."&lang=zh_CN";

      $data = file_get_contents($url);

      $data = json_decode($data,true);

      return $data;
    }

    public function qqlogin()
    {
        qqlogin();
    }

    public function qqreturn()
    {
        $openid = getOpenId();

        $user = M('user')->where(['openid'=>$openid])->find();


        if($user){

          $_SESSION['uid'] = $user['uid'];
          $_SESSION['nickname'] = $user['nickname'];
          $_SESSION['face'] = $user['face'];

          $this->success('登录成功',U('home/index/index'));

        }else{

          $user = getUserInfo();

          $face = $this->getFace($user['figureurl_qq_2']);

          $data['nickname'] = $user['nickname'];
          $data['face'] = $face;
          $data['city'] = $user['city'];
          $data['sex'] = $user['gender'];
          $data['ctime'] = time();
          $data['openid'] = $openid;

          $uid = M('user')->add($data);


          $_SESSION['uid'] = $uid;
          $_SESSION['nickname'] = $data['nickname'];
          $_SESSION['face'] = $data['face'];

          $this->success('登录成功',U('home/index/index'));

        }



    }

    public function text($value='')
    {
      // APP ID：101428693
// APP Key：1a194a1ddc14faf6340530e3aef5d03e
// http://1o533n8683.imwork.net/P201704/bbs/index.php/home/login/qqreturn
// 
      // 申请权限
      // 下载sdk
      // 配置参数
      // 跳转到qq平台
      // 回调到网站 拿openid
      // 判断用户是否存在
      // 直接生成一个新帐号（下载头像）
    }

    public function getFace($path)
    {

        $dir = "Uploads/".date('Y-m-d').'/';

        is_dir($dir) || mkdir($dir);

        $face = $dir.uniqid().'.png';



        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $path);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);


        $output = curl_exec($ch);

        curl_close($ch);

        file_put_contents($face, $output);

        return $face;
        
    }
}